<?php


namespace payment;


use app\service\ImUserService;
use think\facade\Log;

class ImPay
{

    // 插件配置参数
    private $config;

    /**
     * [__construct 构造方法]
     * @param   [string]     $app_id         [应用appid]
     * @param   [string]     $app_secret     [应用密钥]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2017-12-30T18:04:05+0800
     */
    public function __construct($params = [])
    {
        $this->config = $params;
    }

    public function divide($params = [])
    {
        $b = [
            [
                "amount"    => $params['amount'],
                "ledgerName"    => "解炎",
                "ledgerNo"    => "10034366168",
            ]
        ];
        $bs = json_encode($b, JSON_UNESCAPED_UNICODE);

        $a = [
            //"account"                   => "164931889277666",//线下支付
            "account"                   => "164983347577815",//线上支付
            "upOrderId"                 => $params['up_order_id'],
            "lowDivideOrderId"          => $params['order_no'],
            "isUnfreezeResidualAmount"  => "FALSE",
            "divideDetail" =>  $bs

        ];
        $a['sign'] = self::sign_online($a);
        $requestUrl = "/tgPosp/commonDivide/divide";
        $jsonStr = json_encode($a, JSON_UNESCAPED_UNICODE);
        $res = self::httpJson($requestUrl, $jsonStr);
        return $res;
    }


    public function Pay($params = [])
    {
        //return json(['code' => 0, 'msg' => 'dddd', 'data' => $params]);
        // 参数
        if(empty($params))
        {
            return DataReturn('参数不能为空', -1);
        }

        // 配置信息
        if(empty($this->config))
        {
            return DataReturn('支付缺少配置', -1);
        }
        $a = [
            "account"           => "164931889277666", //线下支付
            //"account"           => "164983347577815",//线上支付
            "payMoney"          => $params['total_price'],
            "lowOrderId"        => $params['order_no'],
            "notifyUrl"         => $params['notify_url'],
            "body"              => '商品',
            "returnUrl"         => $params['redirect_url'],
            "payType"           => "1",
            "appId"             => "wx0ca24c69c47958eb",
            "openId"            => $params['user']['weixin_openid'],
            "isMinipg"          => "1",
            "fundProcessType"   => "DELAY_SETTLE"
        ];
        $a['sign'] = self::sign($a);
        $requestUrl = "/tgPosp/services/payApi/wxJspay";
        $jsonStr = json_encode($a,JSON_UNESCAPED_UNICODE);
        $res = self::httpJson($requestUrl, $jsonStr);

        return DataReturn('', 0,$res);
    }

    public static function sign($a)
    {
        $key = '1b8d79d920ae2285ab14dcb873fbb047';//线下支付
        //$key = 'b2d1e06382ea4ffe2cbb5282c6013ea6';//线上支付
        ksort($a);
        $str = '';
        foreach($a as $k => $v){
            $str .= ($k.'='.$v.'&');
        }
        $str = substr($str,0,-1);
        $str .= '&key='.$key;
        $a = strtoupper(md5($str));
        return $a;

    }

    public static function sign_online($a)
    {
        //$key = '1b8d79d920ae2285ab14dcb873fbb047'; //线下支付
        $key = 'b2d1e06382ea4ffe2cbb5282c6013ea6';//线上支付
        ksort($a);
        $str = '';
        foreach ($a as $k => $v) {
            $str .= ($k . '=' . $v . '&');
        }
        $str = substr($str, 0, -1);
        $str .= '&key=' . $key;
        $a = strtoupper(md5($str));
        return $a;
    }

    public static function httpJson($url, $jsonStr)
    {
        try{
            $url = 'https://tgpay.833006.net' .$url;
            //$url = 'https://tgpay.833006.net' .$url;
            //$url = 'http://tgyapi.yltg.com.cn/mock/347'.$url;
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json; charset=utf-8',
                    'Content-Length: ' . strlen($jsonStr)
                )
            );
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            return json_decode($response,true);
            return array($httpCode, json_decode($response,true));
        }catch (\Exception $e){

        }
        return [];

    }


    public function Respond($params = [])
    {

        try{
            $result = file_get_contents('php://input');
            Log::record('支付回调数据 '.$result);
            $result = json_decode($result,true);

            $signData = $result;
            unset($signData['sign'],$signData['payoffType'],$signData['settlementChannel']);

           // $syncCharge = ImUserService::charge($result);
            if(isset($result['state']) && $result['state'] == 0 && $result['sign'] === self::sign($signData))
            {

                return DataReturn('支付成功', 0, $this->ReturnData($result));
            }
        }catch(\Exception $e){

            print_r($e->getMessage());

        }
        return DataReturn('处理异常错误', -100);

    }


    private function ReturnData($data)
    {
        // 返回数据固定基础参数
        $data['trade_no']       = $data['upOrderId'];  // 支付平台 - 订单号
        $data['buyer_user']     = $data['openid'];          // 支付平台 - 用户
        $data['out_trade_no']   = $data['lowOrderId'];    // 本系统发起支付的 - 订单号
        $data['subject']        = $data['attach'] ?? '';          // 本系统发起支付的 - 商品名称
        $data['pay_price']      = $data['payMoney'];   // 本系统发起支付的 - 总价
        return $data;
    }


    /**
     * [HttpRequestGet get请求]
     * @param    [string]           $url [url地址]
     * @return   [array]                 [返回数据]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2018-01-03T19:21:38+0800
     */
    public function HttpRequestGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);
        return json_decode($res, true);
    }

    /**
     * [HttpRequestPost curl模拟post]
     * @param    [string]   $url        [请求地址]
     * @param    [array]    $data       [发送的post数据]
     * @param    [array]    $is_parsing [是否需要解析数据]
     * @return   [array]                [返回的数据]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2017-09-25T09:10:46+0800
     */
    public function HttpRequestPost($url, $data, $is_parsing = true)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_POST, true);

        $res = curl_exec($curl);
        if ($is_parsing === true) {
            return json_decode($res, true);
        }
        return $res;
    }

}
